/**
 * 注册Service Worker
 * @param {string} swPath - Service Worker文件路径
 */
export const registerServiceWorker = (swPath = '/service-worker.js') => {
  if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
      navigator.serviceWorker.register(swPath)
        .then(registration => {
          console.log('ServiceWorker registration successful:', registration.scope);
          registration.update(); // 立即检查更新
        })
        .catch(err => {
          console.log('ServiceWorker registration failed: ', err);
        });
    });
  }
};

/**
 * 缓存管理工具
 */
export const cacheManager = {
  // 设置缓存
  set: (key, data, ttl = 3600) => {
    try {
      const item = {
        data,
        expires: Date.now() + ttl * 1000,
        version: 1
      };
      localStorage.setItem(key, JSON.stringify(item));
      return true;
    } catch (e) {
      console.error('LocalStorage set error:', e);
      return false;
    }
  },

  // 获取缓存
  get: (key) => {
    try {
      const itemStr = localStorage.getItem(key);
      if (!itemStr) return null;
      
      const item = JSON.parse(itemStr);
      if (Date.now() > item.expires) {
        localStorage.removeItem(key);
        return null;
      }
      
      return item.data;
    } catch (e) {
      console.error('LocalStorage get error:', e);
      return null;
    }
  },

  // 删除缓存
  remove: (key) => {
    localStorage.removeItem(key);
  },

  // 清空过期缓存
  clearExpired: () => {
    Object.keys(localStorage).forEach(key => {
      try {
        const item = JSON.parse(localStorage.getItem(key));
        if (item && item.expires && Date.now() > item.expires) {
          localStorage.removeItem(key);
        }
      } catch (e) {
        // 忽略非JSON数据
      }
    });
  }
};

/**
 * 为静态资源添加版本号
 * @param {string} url - 资源URL
 * @param {string} version - 版本号
 */
export const versionResource = (url, version = 'v1') => {
  if (!url) return url;
  const separator = url.includes('?') ? '&' : '?';
  return `${url}${separator}_v=${version}`;
};
